<?php
define("HOST", "localhost");
define("USERNAME", "zhengyu");
define("PASSWORD", "zy476781164");
define("DBNAME", "cis");

$db = new mysqli(HOST, USERNAME, PASSWORD, DBNAME);

//输入一个关联数组（字段：数据）;查询出所有的记录，并返回数组
function select($ary, $table, $all=false){
	global $db;

	if(is_array($ary)){
		$db->query('SET NAMES UTF8');

		$selectStr = 'SELECT ';

		$keys = array_keys($ary);
		$values = array_values($ary);

		//判断数组是否为空
		if(count($keys) != 0 && count($values) != 0){
			//是否查询全部
			if(!$all){
				for($i = 0; $i < count($keys); $i++){
					if($i == count($keys) - 1){
						$selectStr = $selectStr.$keys[$i].' From '.$table;
					}else{
						$selectStr = $selectStr.$keys[$i].', ';
					}
				}
			}else{
				$selectStr = $selectStr.'* FROM '.$table;
			}
			
			$selectStr = $selectStr.' where ';
			//where条件
			for($j = 0; $j < count($values); $j++){
				$selectStr = $selectStr.$keys[$j] ;
			}

			return $selectStr;
		}else{
			return '';
		}


	}else{
		return '';
	}
}


function queryStr($sqlStr){
	global $db;

	//关键，用于防止乱码
	$db->query('SET NAMES UTF8');

	$result = $db->query($sqlStr);

	$result_ary = array();

	$nums = $result->num_rows;

	$result_ary['num_rows'] = $nums;

	$result_ary['rows'] = array();

	for($i = 0; $i < $result->num_rows; $i++){
		$row = $result->fetch_assoc();

		$result_ary['rows'][] = $row;
	}

	return $result_ary;
}


//执行insert、update、delete等操作，返回布尔值
function insert($sqlStr){
	global $db;

	//关键，用于防止乱码
	$db->query('SET NAMES UTF8');
	
	$result = $db->query($sqlStr);
	
	if($result != ''){
		return true;
	}else{
		return false;
	}
}



//通过表名查询出所有信息
function getAll($table_name){
	$sql = "select * from $table_name";

	$result = queryStr($sql);

	if($result['num_rows'] != 0){
		return $result['rows'];
	}

	return '';
}


function prepareInsert($sql, $ary){
	$db = new PDO('mysql:host='.HOST."; dbname=".DBNAME, USERNAME, PASSWORD);

	//关键，用于防止乱码
	$db->query('SET NAMES UTF8');

	$stmt = $db->prepare($sql);

	for($i = 0; $i < count($ary); $i++){
		$stmt->bindParam($i + 1, $ary[$i]);
	}

	return $stmt->execute();
}
?>